<?php

namespace home\controller;

use home\model\BlogModel;

class BlogController extends Controller{

    private $blog;

    public function __construct(){
        $this->blog = new BlogModel();
    }
     //查找指定id的用户并调用viwe显示
     public function getBlog($params){
        $data = $this->blog->getBlog($params);
        if(!$data){
            header('Location:/blog_system/home/view/404.php');
        }
        $this->setData($data);
        return $this->view('info');
    }
    /**
     * 显示主页
     */
    public function getBlogindex($params = null){
        $data = $this->blog->getBlogPage($params);
        if(!$data){
            header('Location:/blog_system/home/view/404.php');
        }
        $this->setData('blogs',$data);
        return $this->view('index');
    }
    //查询数据库中的 指定页码 用户信息并调用viwe显示
    public function getBlogPage($params = array('page' => 0)){
        $data = $this->blog->getBlogPage($params);
        return json_encode($data); 
    }
    //模糊查询博客信息以 JSON 形式返回
    public function queryBlog($params){
        $data = $this->blog->queryBlog($params);
        $len = count($data,0);
        if($len != 0){
            for($i=0;$i<$len;$i++){
                $data[$i]['title'] = str_ireplace($params['key'],"<span style='background-color: #cccc;'>{$params['key']}</span>",$data[$i]['title']);
                $data[$i]['outline'] = str_ireplace($params['key'],"<span style='background-color: #cccc;'>{$params['key']}</span>",$data[$i]['outline']);
            }
        }
        return json_encode($data);
    }
    /**
     * 查询指定类别信息的博客信息
     */
    public function queryTypeBlog($params){
        $data = $this->blog->queryTypeBlog($params['id']);
        return json_encode($data);
    }

    /**
     * 获取数据
     * type = 1 获取点赞排行数据
     * type = 2 获取推荐排行数据
     * type = 3 获取文章分类数据
     * 否则返回 404 代码
     */
    public function queryJson($params){
        if($params['type'] == 1){
            $data = $this->blog->queryPraise();
        }else if($params['type'] == 2){
            $data = $this->blog->queryRead();
        }else if($params['type'] == 3){
            $data = $this->blog->queryType();
        }else{
            $data = array('code'=>404);
        }
        return json_encode($data); 
    }
    /**
     * 添加阅读数量
     */
    public function addCount($params){
        if($params['type'] == 1){
            $this->blog->addRead($params);
            $data = $this->db->num;
        }else if($params['type'] == 2){
            $this->blog->addPrasise($params);
            $data = $this->db->num;
        }else{
            $data = array('code'=>404);
        }
        return json_encode($data); 
    }
    
}